package com.zhuhjay.eduservice.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zhuhjay.eduservice.entity.EduSubject;
import com.zhuhjay.eduservice.entity.excel.SubjectData;
import com.zhuhjay.eduservice.service.EduSubjectService;
import com.zhuhjay.servicebase.exception.GuLiException;
import org.springframework.util.ObjectUtils;

/**
 * @author ZhuHJay
 * @date 2022/9/6 17:57
 */
public class SubjectExcelListener extends AnalysisEventListener<SubjectData> {

    private final EduSubjectService subjectService;
    public SubjectExcelListener(EduSubjectService subjectService) {
        this.subjectService = subjectService;
    }

    @Override
    public void invoke(SubjectData data, AnalysisContext context) {
        if (ObjectUtils.isEmpty(data)) {
            throw new GuLiException(20001, "文件数据为空");
        }
        // 一行一行读取，一个为一级分类，一个为二级分类
        // 分类不可重复添加，需要判断分类是否重复
        EduSubject oneSub = this.getSubject(data.getOneSubjectName(), "0");

        // 判断一级分类是否存在
        if (ObjectUtils.isEmpty(oneSub)) {
            oneSub = new EduSubject().setTitle(data.getOneSubjectName()).setParentId("0");
            this.subjectService.save(oneSub);
        }

        EduSubject twoSub = this.getSubject(data.getTwoSubjectName(), oneSub.getId());
        // 判断二级分类是否存在
        if (ObjectUtils.isEmpty(twoSub)) {
            twoSub = new EduSubject().setTitle(data.getTwoSubjectName()).setParentId(oneSub.getId());
            this.subjectService.save(twoSub);
        }
    }

    /**
     * 根据类别名称和父ID找到类别信息
     * @param title 类别名称
     * @param parentId 父ID，0为顶层
     */
    private EduSubject getSubject(String title, String parentId) {
        return this.subjectService.getOne(new LambdaQueryWrapper<EduSubject>()
                .eq(EduSubject::getTitle, title)
                .eq(EduSubject::getParentId, parentId)
        );
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {

    }
}
